<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="listDevice"
    :columns="columns"
    row-key="deviceId"
    :onValuesChange="changeFormState"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onOpenRules()" code="accessRules:list"
          >接入规则</b-button
        >
        <b-button icon="delete" @click="onDelete()" code="device:remove"
          >全部清除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        :disabled="record.checkStatus == '1'"
        @click="onView(record)"
        code="device:edit"
        >校验</b-button
      >
      <b-button
        icon="del"
        type="link"
        @click="onDelete(record)"
        code="device:remove"
        >清除</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
  <Modal
    title="接入规则"
    v-model:open="rulesVisible"
    :width="1100"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
  >
    <Rules :projectData="projectData" />
  </Modal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { DatePicker, Modal, Select, Space, Tag, message } from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, listToOption } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import {
  delAllDevice,
  delDevice,
  getModel,
  listDevice,
  updateDevice,
} from '@/api/device';
import { fetchDictsOfType } from '@/api/dict';
import { getModelInfoById } from '@/api/push';
import Rules from './components/Rules.vue';

const tableRef = ref();
const rulesVisible = ref(false);
const sysDeviceModeEnum = ref<Record<string, any>>({});
const getModelOptions = ref<Global.Option[]>([]);
const sysDeviceModeOption = ref<Global.Option[]>([]);
const sysCheckStateEnum = ref<Record<string, any>>({});
const sysOnlineStatusEnum = ref<Record<string, any>>({});
const modListEnum = ref<Record<string, any>>({});
const modListAllEnum = ref<Record<string, any>>({});
const modListOption = ref<Global.Option[]>([]);
const projectData = ref([]);
const init = () => {
  fetchDictsOfType([
    'sys_device_mode',
    'sys_check_state',
    'sys_on_line_status',
  ]).then((res: any) => {
    const { sys_device_mode, sys_check_state, sys_on_line_status } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
    getModelOptions.value = listToOption(
      sys_device_mode,
      'dictLabel',
      'dictValue',
    );
    sysDeviceModeOption.value = listToOption(
      sys_device_mode,
      'dictLabel',
      'dictValue',
    );
    sysCheckStateEnum.value = listToEnum(
      sys_check_state,
      'dictValue',
      'dictLabel',
    );
    sysOnlineStatusEnum.value = listToEnum(
      sys_on_line_status,
      'dictValue',
      'dictLabel',
    );
  });
  getModel().then((res: any) => {
    modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    modListAllEnum.value = listToEnum(res.data, 'modelId', 'model');
    modListOption.value = listToOption(res.data, 'model', 'modelId', 'string');
  });

  const addDisableProperty = (tree: any) => {
    tree.forEach((item: any) => {
      if (item.type === '1') {
        item.disabled = true;
        item.selectable = false;
      }
      if (item.children) {
        addDisableProperty(item.children);
      }
    });
  };
  getProjectData().then((res: any) => {
    projectData.value = res.data;
    addDisableProperty(projectData.value);
  });
};
init();
const changeFormState = async (formState: any) => {
  if (formState.deviceType) {
    console.log(formState.deviceType, 'deviceType');

    const res = await getModelInfoById({
      type: formState.deviceType,
      modelIds: '',
    });
    modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    modListOption.value = listToOption(res.data, 'model', 'modelId', 'string');
  } else {
    modListOption.value = [];
  }
};

const columnsOptions = computed(() => {
  return modListOption.value.length
    ? modListOption.value
    : getModelOptions.value;
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '接入时间',
    dataIndex: 'accessTime',
    customSearchRender(state) {
      return (
        <DatePicker
          v-model:value={state.accessTime}
          valueFormat='YYYY-MM-DD'
          onChange={(date) => {
            state.accessTime = date || undefined;
          }}
        />
      );
    },
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: { ...sysDeviceModeEnum.value },
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <Select
          v-model:value={state.modelId}
          options={columnsOptions.value}
        ></Select>
      );
    },
  },
  {
    title: '校验状态',
    dataIndex: 'checkStatus',
    hideInSearch: true,
    width: 100,
    customRender({ text }) {
      return (
        <Tag
          color={text == '0' ? 'warning' : text == '1' ? 'success' : 'error'}
        >
          {
            sysCheckStateEnum.value?.[
              text as keyof typeof sysCheckStateEnum.value
            ]
          }
        </Tag>
      );
    },
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    width: 100,
    valueEnum: { ...sysOnlineStatusEnum.value },
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'error' : 'processing'}>
          {
            sysOnlineStatusEnum.value?.[
              text as keyof typeof sysOnlineStatusEnum.value
            ]
          }
        </Tag>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 150,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '设备序列号',
    type: 'input',
    field: 'code',
    disabled: true,
  },
  {
    label: '固件版本',
    type: 'input',
    field: 'firmwareVersion',
    disabled: true,
  },
  {
    label: '设备类型',
    type: 'select',
    field: 'deviceType',
    props: {
      options: sysDeviceModeOption.value,
    },
    disabled: true,
  },
  {
    label: '设备型号',
    type: 'select',
    field: 'modelId',
    props: {
      options: modListOption.value,
    },
    disabled: true,
  },
  {
    label: '所属项目',
    type: 'treeSelect',
    field: 'projectId',
    rules: [
      {
        required: true,
        message: '请选择所属项目',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择所属项目',
      treeData: projectData.value,
      fieldNames: {
        value: 'id',
      },
    },
  },
  {
    label: '是否通过',
    type: 'radio',
    field: 'checkStatus',
    rules: [
      {
        required: true,
        message: '请选择是否通过',
        trigger: 'blur',
      },
    ],
    props: {
      options: [
        { label: '通过', value: '1' },
        { label: '拒绝', value: '2' },
      ],
    },
    // disabled(state) {
    //   return state.checkStatusDisabled;
    // },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
  formProps: { labelCol: { span: 4 } },
});
const onView = (record: any) => {
  console.log(record.checkStatus, 'record.checkStatus');
  open({
    title: '效验',
    defaultValue: {
      ...record,
      checkStatus: ['1', '2'].includes(record.checkStatus)
        ? record.checkStatus
        : null,
      checkStatusDisabled: record.checkStatus == 2 ? true : false,
    },
    serviceApi: async (params: any): Promise<any> => {
      await updateDevice(params);
      tableRef.value.refresh();
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (record?: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: record ? '是否确认删除当前设备？' : '是否确认全部删除设备？',
    onOk: async () => {
      if (record) {
        await delDevice(record.deviceId);
      } else {
        await delAllDevice();
      }
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
const onOpenRules = () => {
  rulesVisible.value = true;
};
</script>
